package cn.briarbear.myblog.controller;

import cn.briarbear.myblog.entity.Image;
import cn.briarbear.myblog.enums.ViewConsts;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSON;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

@Controller
public class PageController {

    @GetMapping("/hello")
    public String  hello(Model model) throws Exception{
        model.addAttribute("name","xiongzp08");
//        throw new MyException("404");
        return "hello";
    }

    @RequestMapping({"/","/index"})
    public String index(HttpServletRequest request,Model model) throws IOException {

        //获取图片列表
        URL url = new URL("http://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=3&mkt=zh-CN");
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(),"UTF-8"));
        StringBuffer sb = new StringBuffer();
        String temp;
        while ((temp = br.readLine())!=null){
            sb.append(temp);
        }
        String result = new String(sb);
        JSON json = (JSON) JSON.parse(result);
        String images = JSON.parseObject(result).getString("images");
        List<Image> list = JSON.parseArray(images,Image.class);

        String website = "http://www.bing.com";
        List<Image> imageList = new ArrayList<>();
        for (Image image : list) {
            String imageUrl = image.getUrl();

            String[] copyRight = image.getCopyright().split("[(,（]");
            image.setMoto_CN(copyRight[0]);
            image.setMoto_US("("+copyRight[1]+ "---------来自 Bing---每日美图");
            image.setUrl(website+imageUrl);
            imageList.add(image);
        }

        model.addAttribute(ViewConsts.VIEW_IMAGELIST,imageList);
        return "index";

    }



    @GetMapping("/love")
    public String love(){
        return "love";
    }
}
